<template>

	<view class="page">
		<uni-card margin='2px' style="margin-bottom: 20px; padding: 5px;padding-bottom: 30px;">
			<view class="card-title">1.基础信息</view>

			<mpopupHeaderRadioItem label="考核人姓名" height="90px" :custom-class="'custom-align'"
				:custom-style="{ padding: '10rpx' }">
				<input placeholder="请填写考核人姓名" v-model="formItem.assessorName" class="wide-input" />
			</mpopupHeaderRadioItem>

			<mpopupHeaderRadioItem label="考核人证件号" height="90px" :custom-class="'custom-align'"
				:custom-style="{ padding: '20rpx' }">
				<input placeholder="请填写考核人证件号" v-model="formItem.assessorCertNo" class="wide-input" />

			</mpopupHeaderRadioItem>
			<mpopupHeaderRadioItem label="考核人职位" height="90px" :custom-class="'custom-align'"
				:custom-style="{ padding: '20rpx' }">
				<input placeholder="请填写考核人职位" v-model="formItem.assessorPosition" class="wide-input" />

			</mpopupHeaderRadioItem>
			<mpopupHeaderRadioItem label="其他信息A" height="90px" :custom-class="'custom-align'"
				:custom-style="{ padding: '20rpx' }">

				<input placeholder="请填写其他信息A" v-model="formItem.otherInfoA" class="wide-input" />

			</mpopupHeaderRadioItem>
			<mpopupHeaderRadioItem label="其他信息B" height="90px" :custom-class="'custom-align'"
				:custom-style="{ padding: '20rpx' }">

				<input placeholder="请填写其他信息B" v-model="formItem.otherInfoB" class="wide-input" />
			</mpopupHeaderRadioItem>
			<mpopupHeaderRadioItem label="其他信息C" height="90px" :custom-class="'custom-align'"
				:custom-style="{ padding: '20rpx' }">
				<input placeholder="请填写其他信息C" v-model="formItem.otherInfoC" class="wide-input" />

			</mpopupHeaderRadioItem>
			<mpopupHeaderRadioItem :show-bottom-border="true" label="参与考核日期" height="90px"
				:custom-class="'custom-align'" :custom-style="{ padding: '20rpx' }">
				<uni-datetime-picker type="date" @change="handleDateChange" />
			</mpopupHeaderRadioItem>
			<button v-show="editStatus=='ADD'" style="margin-top: 40px;" type="primary" @click="handleToReprot">
				保存基础信息</button>

			<button style="margin-top: 10px;margin-bottom: 90px;" type="primary" @click="getQuestionList"> 生成题目</button>



			<view class="card-title">2.考核题目</view>

			<view class="content-text">{{ this.questionlist.copywriting}}</view>
			<view>

				<!-- 循环渲染题目 -->
				<mpopupHeaderRadioItem v-for="(item, index) in this.questionlist.list" :key="item.id"
					:label="item.content" :custom-class="'custom-align'" :custom-style="{ padding: '20rpx' }"
					:show-bottom-border="index === questionlist.list.length - 1">
					<template>
						<!-- 动态绑定选项 -->
						<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" mode="list"
							v-model="selectedAnswers[index]" :localdata="formatOptions(item)"></uni-data-checkbox>
					</template>
				</mpopupHeaderRadioItem>
			</view>
		</uni-card>
		<!-- 二维码弹窗 -->
		<uni-popup ref="qrPopup" type="center" @touchmove.stop.prevent>
			<view class="qr-popup">
				<!-- 动态绑定二维码图片 -->
				<image :src="qrcodeUrl" mode="widthFix" class="qrcode-img" @error="handleImageError"></image>
				<view class="popup-buttons">
					<button type="warn" @click="closeQRPopup">关闭</button>
				</view>
			</view>
		</uni-popup>
		<view>
			<button style="margin-bottom: 10px;" type="primary" @click="generateQrcode">确认并生成考试二维码</button>
			<button v-if='isShowBtn' style="margin-bottom: 10px;" type="primary"
				@click="handleIdentityVerify">获取考核结果</button>
			<button type="warn" @click="goHome">取消并返回创建工单页</button>
		</view>


		<!-- 身份验证弹窗 -->
		<uni-popup ref="verifyPopup" type="center" >
			<view class="verify-dialog">
				<!-- 标题 -->
				<view class="dialog-header">
					<text class="title">质量负责人现场考核结果</text>
				</view>

				<text
					style="margin: 15px;font-size: 17px;margin-top: 20px;">尊敬的用户,您已完成本次考核，是否将您的答题结果上传至服务器？若您有其他疑问或需求,请与现场核查人员进行沟通。您的考核成绩如下。</text>
				<!-- 表格区域 -->
				<view class="table-container">
					<!-- 添加横向滚动容器 -->
					<scroll-view scroll-x="true" class="scroll-wrapper">
						<uni-table border stripe :style="{minWidth: '600rpx'}" class="adaptive-table">
							<uni-tr class="table-header">
								<uni-th v-for="(col,index) in columns" :key="index" :style="{flex: `0 0 ${col.width}%`}"
									class="nowrap-cell">{{col.title}}</uni-th>
							</uni-tr>

							<!-- 数据行动态适配 -->
							<uni-tr v-for="(item,index) in verifyRecordsArray" :key="index" class="data-row">
								<uni-td v-for="(col, colIndex) in columns" :key="colIndex"
									:style="{flex: `0 0 ${col.width}%`}" class="wrap-cell">{{ item[col.key] }}</uni-td>
								<!-- 关键修正：使用 col.key -->
							</uni-tr>
						</uni-table>
					</scroll-view>
				</view>
				<!-- 操作按钮 -->
				<view class="dialog-footer">
					<button type="primary" @click="updateAuditStatus">提交本次质量负责人现场考核结果</button>
				</view>
			</view>
		</uni-popup>
	</view>

</template>

<script>
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	import mpopupHeaderItem from "@/components/mpopup-header-item.vue"
	import mpopupHeaderRadioItem from "@/components/mpopup-header-radio-item.vue"
	import mpopupTable from "@/components/mpopup-table.vue"
	import UQRCode from 'uqrcodejs'; // npm install uqrcodejs
	import {
		updateAuditStatus,
		examRecord,
		getQuestionList,
		questionsNum,
		generateQrcode,
		questionGetList,
		medicalUpdate
	} from '@/api/order'
	export default {
		components: {
			mpopupHeaderRadioItem,
			mpopupHeaderItem, // 需先导入组件
			mpopupTable
		},
		data() {
			return {
				columns: [{
						title: '姓名',
						key: 'userName',
						width: 15
					},
					{
						title: '证件号',
						key: 'certNo',
						width: 25
					},
					{
						title: '合格分数',
						key: 'severalScores',
						width: 20
					},
					{
						title: '最终得分',
						key: 'score',
						width: 20
					},
					{
						title: '考核结果',
						key: 'examResults',
						width: 20
					}
				],
				tableMinWidth: 300, // 根据列数动态计算

				questionlist: {
					list: [], // 确保初始有list属性
					copywriting: '',
				},

				qrcodeUrl: '', // 存储二维码URL
				selectedAnswers: [], // 存储用户选择的答案
				showQRCode: false, // 控制二维码显示
				qrContent: '', // 二维码内容
				operatorName: '自动生成',
				address: '自动生成',
				number: '自动生成',
				type: '自动生成',
				isShowBtn: false,
				formItem: {
					assessorName: '',
					assessorCertNo: '',
					assessorPosition: '',
					otherInfoA: '',
					otherInfoB: '',
					otherInfoC: '',
					assessmentDate: '', // 新增验证记录数据
					workOrderId: ''
				},
				workOrderId: '',
				verifyRecords: {},
				verifyRecordsArray: [],
				editStatus: 'ADD',
				isSave: false,
			}
		},
		onLoad(options) {
			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);
				const qualityManagerCertNo = decodeURIComponent(options.qualityManagerCertNo);
				const qualityManagerName = decodeURIComponent(options.qualityManagerName);


				this.formItem.workOrderId = workOrderId;
				this.workOrderId = workOrderId;
				this.editStatus = editStatus;
				this.formItem.assessorName = qualityManagerName;
				this.formItem.assessorCertNo = qualityManagerCertNo;
				this.isShowBtn = true;
				this.getQuestionlInfo(workOrderId);
			} else {
				const orderid = decodeURIComponent(options.workOrderId);
				this.workOrderId = orderid;
				this.formItem.workOrderId = orderid;
			}
		},
		methods: {

			// 获取医疗器械工单详情
			async getQuestionlInfo(orderId) {
				const id = {
					workOrderId: orderId
				}
				const res = await questionGetList(id);
				if (res.code === 0) {
					this.questionlist.list = res.data.list

				}
			},
			// 将选项格式转换为 uni-data-checkbox 需要的结构[1,2](@ref)
			formatOptions(item) {
				return [{
						text: item.optionA,
						value: 'A'
					},
					{
						text: item.optionB,
						value: 'B'
					},
					{
						text: item.optionC,
						value: 'C'
					},
					{
						text: item.optionD,
						value: 'D'
					}
				]
			},
			async handleIdentityVerify() {
				this.formItem.workOrderId = this.workOrderId
				try {
					const orderId = {
						workOrderId: this.formItem.workOrderId
					};
					const res = await examRecord(orderId)

					if (res.code === 0) {
						if (res.data.examResults === 0) {
							res.data.examResults = '不合格';
						} else {
							res.data.examResults = '合格';
						}
						console.log(this.verifyRecords)
						this.verifyRecords = res.data
						this.verifyRecordsArray.push(this.verifyRecords);
					}
				} catch (error) {
					uni.showToast({
						title: '失败',
						icon: 'none'
					})
				}
				this.$refs.verifyPopup.open()
			},
			closeVerifyDialog() {
				this.$refs.verifyPopup.close()
			},
			handleToQR() {
				uni.showToast({
					title: '题目生成成功'
				})
				// 显示二维码容器
				this.showQRCode = true
				// 生成二维码内容（示例使用返回的ID）
				this.qrContent = `https://your-exam-page.com/exam?id`

				// 显示弹窗
				this.$refs.qrPopup.open()
				// 延迟确保canvas渲染完成
				setTimeout(() => {
					this.generateQRCode()
				}, 300)
				// 生成二维码
				this.$nextTick(() => {
					this.generateQRCode()
				})
			},
			// 生成二维码方法
			generateQRCode2() {
				const qr = new UQRCode()
				qr.data = this.qrContent
				qr.size = 200
				qr.make()

				const canvasContext = uni.createCanvasContext('qrcode', this)
				qr.canvasContext = canvasContext
				qr.drawCanvas()
			}, // 关闭弹窗
			closeQRPopup() {
				this.isShowBtn = true;
				this.$refs.qrPopup.close()

			},
			handleDateChange(date) {
				this.formItem.assessmentDate = date
			},

			//生成二维码
			async generateQrcode() {
				try {

					/*
					if(this.editStatus==='ADD'){
						// 关键字段校验
						if (!this.formItem.assessorName && !this.formItem.assessorCertNo) {
							uni.showToast({
								title: '请先填写考核人姓名和证件号',
								icon: 'none',
								duration: 2000
							});
							return;
						}
						
						// 自动保存基础信息
						const saveRes = await questionsNum(this.formItem);
						if (saveRes.code !== 0) {
							throw new Error(saveRes.msg || '基础信息保存失败');
						}
					}
				*/
					this.formItem.workOrderId = this.workOrderId

					// 生成二维码
					const querList = {
						businessId: this.formItem.workOrderId,
						userName: this.formItem.assessorName,
						certNo: this.formItem.assessorCertNo
					};
					console.log("querList")
					console.log(querList)

					const qrRes = await generateQrcode(querList);
					if (qrRes.code === 0) {
						this.qrcodeUrl = qrRes.data;
						this.$refs.qrPopup.open();
					} else {
						throw new Error(qrRes.msg || '二维码生成失败');
					}
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none',
						duration: 2000
					});
				}
			},
			//保存考核基础信息
			async handleToReprot() {
				this.formItem.workOrderId = this.workOrderId
				// 前置校验逻辑独立（避免与业务逻辑耦合）
				if (!this.isSave && (!this.formItem.assessorName || !this.formItem.assessorCertNo)) {
					uni.showToast({
						title: '请先填写考核人姓名和证件号',
						icon: 'none'
					});
					return;
				}
				if (this.editStatus === 'FALSE') {
					uni.showToast({
						title: '当前处于查看状态',
						icon: 'none'
					});
					return;
				}

				try {
					let res;
					// 明确操作类型分支
					if (this.editStatus === 'EDIT') {
						res = await medicalUpdate(this.formItem);
					} else if (this.editStatus === 'ADD') {
						res = await questionsNum(this.formItem);
					} else {
						throw new Error(`未知操作状态：${this.editStatus}`);
					}

					// 成功响应处理
					if (res.code === 0) {
						uni.showToast({
							title: '保存信息成功'
						});
						this.isSave = true;
						console.log(res)
						// 建议增加后续操作（如跳转/刷新数据）
						// this.$refs.qrPopup.open();
					} else {
						// 处理业务逻辑错误（非HTTP错误）
						throw new Error(`业务异常：${res.msg || '未知错误'}`);
					}
				} catch (error) {
					// 错误分类处理
					if (error.message.includes('未知操作状态')) {
						uni.showToast({
							title: '系统配置错误，请联系管理员',
							icon: 'none'
						});
					} else if (error.response?.status === 401) {
						uni.showToast({
							title: '登录已过期',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: `生成失败：${error.message}`,
							icon: 'none'
						});
					}
					console.error('提交失败详情：', error); // 关键：记录完整错误栈[3,6](@ref)
				}
			}, //提交考核结果
			async updateAuditStatus() {
				try {
					this.formItem.workOrderId = this.workOrderId
					const querList = {
						id: this.verifyRecords.id, //考试结果主键
						auditStatus: "1" //试卷状态-1：已完成
					}
					const res = await updateAuditStatus(querList)
					if (res.code === 0) {
						uni.showToast({
							title: '提交成功'
						})
						this.$refs.verifyPopup.close()

						
					// 关闭当前页面，跳转到工单页
					this.$closeAndRedirect({
					  url: '/pages/work/history/index'
					});

					}
				} catch (error) {
					uni.showToast({
						title: '生成失败',
						icon: 'none'
					})
				}
			},
			//预生成考核题目
			async getQuestionList() {
				const querList = {
					workorderId: this.formItem.workOrderId,
					userName: this.formItem.assessorName,
					certNo: this.formItem.assessorCertNo
				}

				try {
					const res = await getQuestionList(querList)
					if (res.code === 0) {
						uni.showToast({
							title: '预生成考试题目'
						})
						this.questionlist = res.data;
					}
				} catch (error) {
					uni.showToast({
						title: '生成失败',
						icon: 'none'
					})
				}
			},

			goHome() {
				this.$tab.redirectTo("/pages/work/create/index'");
			}
		}
	}
</script>

<style>
	.page {
		flex: 1;
		background-color: #e9f1fe;
		padding: 20px;
		box-sizing: border-box;
	}

	.card-title {
		margin-top: 30px;
		margin-bottom: 30px;
		font-size: 18px;
		margin-top: 20px;
		font-weight: bold;
		text-align: center;
		color: black;
	}

	/* 新增弹窗样式 */
	.qr-popup {
		background: white;
		padding-left: 90px;
		padding-right: 90px;
		padding-bottom: 50px;
		padding-top: 50px;
		border-radius: 10px;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.title {
		font-size: 18px;
		font-weight: bold;
		color: #333;
		display: flex;
		justify-content: center;
	}

	.popup-buttons {
		margin-top: 20px;
		width: 100%;
		display: flex;
		justify-content: space-around;
	}

	.table-container {
		position: relative;
		padding-bottom: 15px;
		/* 防止滚动条遮挡 */
	}

	.scroll-wrapper {
		max-width: 100vw;
		/* 限制最大宽度 */
		overflow-x: auto;
		/* 保留横向滚动 */
	}

	/* 修改表格容器 */
	.adaptive-table {
		width: 100% !important;
		/* 强制宽度不溢出 */
		min-width: auto !important;
		/* 移除固定最小宽度 */
		table-layout: fixed;
		/* 关键属性[1](@ref) */
	}

	/* 列宽动态计算 */
	.uni-th,
	.uni-td {
		width: 0;
		/* 触发自动宽度计算 */
		min-width: 80px;
		/* 设置最小列宽 */
	}

	/* 表头样式 */
	.table-header {
		display: flex !important;
		background: #e9f1fe;

		.uni-th {
			flex-shrink: 0;
			min-width: 60rpx;
			/* 防止内容挤压 */
			white-space: nowrap;
			/* 表头不换行（网页3方案） */
		}
	}

	/* 数据行样式 */
	.data-row {
		display: flex !important;

		.uni-td {
			flex-shrink: 0;
			word-break: break-all;
			/* 内容自动换行 */
			padding: 8rpx 12rpx;
		}
	}

	/* 响应式适配（网页2的媒体查询方案） */
	@media screen and (max-width: 750px) {
		.nowrap-cell {
			font-size: 12px;
		}

		.wrap-cell {
			font-size: 14px;
		}

		.adaptive-table {
			min-width: 100%;
		}
	}

	/* 操作按钮 */
	.dialog-footer {
		text-align: center;
		padding-top: 15px;
	}

	/* 弹窗样式 */
	.verify-dialog {
		width: 90vw;
		background: #fff;
		border-radius: 12px;
		padding: 20px;
	}

	.content-text {
		text-indent: 2em;
		/* 首行缩进2字符 */
		color: #000;
		/* 字体颜色纯黑 */
		font-weight: 500;
		/* 中等加粗 */
		font-size: 14px;
		/* 可选添加字体大小 */
		line-height: 1.5;
		/* 可选添加行高 */
	}

	/* 新增样式 */
	.wide-input {
		width: 100% !important;
		/* 撑满父容器 */
		min-width: 200px;
		/* 最小宽度 */
		max-width: 400px;
		/* 最大宽度 */

		font-size: 16px;
		border-radius: 4px;
		box-sizing: border-box;
	}

	/* 移动端适配 */
	@media (max-width: 768px) {
		.wide-input {
			min-width: 180px;
			max-width: 100%;
			font-size: 14px;
		}
	}

	/* 调整父容器布局 */
	.custom-align {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.mpopupHeaderRadioItem {
		flex-grow: 1;
		/* 允许扩展 */
	}
</style>